package com.zhsj.OkeHomeConsumption.ui.activity.wallet;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.TextView;


import com.zhsj.OkeHomeConsumption.R;
import com.zhsj.OkeHomeConsumption.adapter.BankAdapter;
import com.zhsj.OkeHomeConsumption.common.Constants;
import com.zhsj.OkeHomeConsumption.common.OkeHomeConsumptionApi;
import com.zhsj.OkeHomeConsumption.empty.BankMessage;
import com.zhsj.OkeHomeConsumption.empty.FormalUserInfo;
import com.zhsj.OkeHomeConsumption.network.HttpClient;
import com.zhsj.OkeHomeConsumption.network.JsonResponseHandler;
import com.zhsj.OkeHomeConsumption.other.TimeChecker;
import com.zhsj.OkeHomeConsumption.other.URLEntity;
import com.zhsj.OkeHomeConsumption.utils.LogUtils;
import com.zhsj.OkeHomeConsumption.utils.SignUtil;

import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by zwj on 2017/10/15.
 * 提现 -- 我的银行卡
 */

public class ExtractMoneyBankFragment extends BaseFragment implements View.OnClickListener{

    /**
     * 计时器
     */
    private TimeChecker timeChecker = null;
    /**
     * 实例化ProgressDrawableAlertDialog
     */
    private ProgressDrawableAlertDialog pDialogUtils = null;
    //左标题
    private TextView topbar_textview_leftitle;
    //标题
    private TextView topbar_textview_title;

    //添加银行卡
    private LinearLayout add_bankcard_text;

    private FormalUserInfo userInfo;

    //银行卡列表
    private List<BankMessage> mBankMessageList;
    private List<BankMessage> mBankMessageServiceList;
    private BankAdapter mBankAdapter;
    private NoScrollListView bank_list;

    //钱包余额
    private String walletBalanceStr;

    //用户所属商户号
    private String oid_partner;

    public static ExtractMoneyBankFragment newInstance(FormalUserInfo userInfo, String walletBalanceStr, String oid_partner) {
        
        Bundle args = new Bundle();
        ExtractMoneyBankFragment fragment = new ExtractMoneyBankFragment();
        args.putSerializable("userInfo",userInfo);
        args.putString("walletBalanceStr", walletBalanceStr);
        args.putString("oid_partner", oid_partner);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        userInfo = (FormalUserInfo) getArguments().getSerializable("userInfo");
        walletBalanceStr = getArguments().getString("walletBalanceStr");
        oid_partner = getArguments().getString("oid_partner");
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view  = inflater.inflate(R.layout.fragment_extractmoney_bank, container, false);
        initView(view);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initListener();
        getBankList(userInfo.getId() + "", "RSA", "D");
        mBankAdapter = new BankAdapter(getActivity(), mBankMessageList);
        bank_list.setAdapter(mBankAdapter);
        bank_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                startForResult(ExtractMoneyFragment.newInstance(userInfo, mBankMessageList.get(position), walletBalanceStr, oid_partner),1);
            }
        });
    }

    private void initView(View view){
        topbar_textview_leftitle = (TextView) view.findViewById(R.id.topbar_textview_leftitle);
        topbar_textview_leftitle.setVisibility(View.VISIBLE);
        topbar_textview_title = (TextView) view.findViewById(R.id.topbar_textview_title);
        topbar_textview_title.setText("我的银行卡");
        add_bankcard_text = (LinearLayout) view.findViewById(R.id.add_bankcard_text);
        bank_list = (NoScrollListView) view.findViewById(R.id.bank_list);
    }

    private void initListener(){
        timeChecker = new TimeChecker(TimeOutHandler.timeOutHandler, Constants.TIME_OUT);
        pDialogUtils = new ProgressDrawableAlertDialog(_mActivity);
        topbar_textview_leftitle.setOnClickListener(this);
        add_bankcard_text.setOnClickListener(this);
        mBankMessageServiceList = new ArrayList<BankMessage>();
        mBankMessageList = new ArrayList<BankMessage>();
    }



    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.topbar_textview_leftitle:
                _mActivity.onBackPressed();
                break;
            case R.id.add_bankcard_text:
                //添加银行卡
                startForResult(AddBankFragment.newInstance(userInfo),2);
                break;
        }
    }

    @Override
    public void onFragmentResult(int requestCode, int resultCode, Bundle data) {
        super.onFragmentResult(requestCode, resultCode, data);
        switch (requestCode){
            case 1:
                if (resultCode == RESULT_OK){
                    setFragmentResult(RESULT_OK, new Bundle());
                    _mActivity.onBackPressed();
                }
                break;
            case 2:
                if (resultCode == RESULT_OK){
                    getBankList(userInfo.getId() + "", "RSA", "D");
                }
                break;
        }
    }

    /**
     * 获取银行卡列表
     * @param user_id 用户编号
     * @param sign_type RSA
     */
    public void getBankList(String user_id, String sign_type, String pay_type) {
        // post传参使用的HashMap
        HashMap<String, String> paramMaps = new HashMap<String, String>();
        // 生成sign值所使用的HashMap
        HashMap<String, String> mSendCodeHashMap = new HashMap<String, String>();
//        mSendCodeHashMap.put("token", Constants.TOKEN);
        mSendCodeHashMap.put("v", Constants.APPVERSION);
        mSendCodeHashMap.put("t", Constants.TIME);
        mSendCodeHashMap.put("deviceId", URLEntity.getInstance().getImei());
        mSendCodeHashMap.put("platform", Constants.PLAFORM);
        mSendCodeHashMap.put("deviceToken", Constants.DEVICETOKEN);
        mSendCodeHashMap.put("client", Constants.CLIENT);
        mSendCodeHashMap.put("user_id", user_id);
        mSendCodeHashMap.put("sign_type", sign_type);
        mSendCodeHashMap.put("pay_type", pay_type);

        LogUtils.e("mSendCodeHashMap", mSendCodeHashMap.toString());
        //post 传参
        paramMaps.put("user_id", user_id);
        paramMaps.put("sign_type", sign_type);
        paramMaps.put("pay_type", pay_type);

        // 网络计时器及线程
        TimeOutHandler.pDialogUtils = pDialogUtils;
        pDialogUtils.show();
        timeChecker.start();
        // 获取sign签名
        Constants.SIGN = SignUtil.getInstance().getSign(mSendCodeHashMap);
        LogUtils.e("mSendCodeHashMap", SignUtil.getInstance().getSign(mSendCodeHashMap));
        HttpClient.post(OkeHomeConsumptionApi.WALLET_BANKLIST, paramMaps, new JsonResponseHandler() {

            @Override
            public void onSuccess(int statusCode, String content) {
                // TODO Auto-generated method stub
                super.onSuccess(statusCode, content);
                timeChecker.check();
                pDialogUtils.dismiss();
                TimeOutHandler.pDialogUtils = null;
                try {
                    LogUtils.e("content_获取银行卡列表", "content=" + content);
                    JSONTokener jsonT = new JSONTokener(content);
                    JSONObject jsonOBJ = (JSONObject) jsonT.nextValue();
                    String code = jsonOBJ.optString("code");
                    String message = jsonOBJ.optString("message");
                    if (code.equals("N000000")) {
                        // 数据对接正常
                        JSONObject jsonObject = jsonOBJ.optJSONObject("data");
                        JSONObject data = jsonObject.optJSONObject("data");
                        JSONArray jsonArray = data.optJSONArray("agreement_list");
                        String ret_code = data.optString("ret_code");
                        if ("0000".equals(ret_code)){
                            mBankMessageServiceList = com.alibaba.fastjson.JSONArray.parseArray(jsonArray.toString(), BankMessage.class);
                            if (mBankMessageServiceList != null && mBankMessageServiceList.size() > 0){
                                mBankMessageList.clear();
                                mBankMessageList.addAll(mBankMessageServiceList);
                                mBankAdapter.notifyDataSetChanged();
                            }
                        }

                    } else if (code.equals(Constants.STATUSTOKENERROR)) {
                        if (!message.equals("null")) {
                            showShortToast(message);
                        }
                    } else {
                        if (!message.equals("null")) {
                            showShortToast(message);
                        }
                    }
                } catch (Exception ex) {
                    LogUtils.e("DresserPartnerRegisterPost", "失败 ");
                }
            }

            @Override

            public void onFailure(Throwable e) {
                // TODO Auto-generated method stub
                super.onFailure(e);
                timeChecker.check();
                pDialogUtils.dismiss();
                TimeOutHandler.pDialogUtils = null;
                LogUtils.e("onFailure", "" + e.toString());
            }
        });
    }
}
